package edu.nf.vac.auth.service;

import edu.nf.vac.auth.exception.AuthenticateException;
import edu.nf.vac.auth.inf.UserTokenService;
import edu.nf.vac.auth.util.JwtUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.SecurityException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.Map;

/**
 * @Author : QYM
 * @create 2022/3/30
 * token认证
 */
@Slf4j
@DubboService(interfaceClass = UserTokenService.class,version = "1.0.0")
public class UserTokenServiceImpl implements UserTokenService{
    /**
     * 创建token
     * @param payload
     * @param tll
     * @return
     */
    @Override
    public String create(Map<String, Object> payload, long tll) {
        //有效一个月的token
        String token = JwtUtils.createToken(payload,1000 * 60 * 60 * 24 * 30);
        return JwtUtils.createToken(payload,tll);
    }

    /**
     * 校验token是否有效
     * @param token
     * @return
     */
    @Override
    public Integer verify(String token) {
        try {
            JwtUtils.verify(token);
            return JwtUtils.getPayload(token,"uid",Integer.class);
        } catch (SecurityException e) {
            throw new AuthenticateException("Invalid JWT signature.");
        }catch (MalformedJwtException e){
            throw new AuthenticateException("Invalid JWT token.");
        }catch (ExpiredJwtException e){
            throw new AuthenticateException("Expired JWT token.");
        }catch (UnsupportedJwtException e){
            throw new AuthenticateException("Unsupported JWT.");
        }catch (IllegalArgumentException e){
            throw new AuthenticateException("JWT token compact of handler are invalid.");
        }
    }
}
